/*
 * Copyright (c) 2022.版权所有高金磊
 */

package 领扣算法.AA中等题.相同元素的间隔之和;

import java.util.ArrayList;
import java.util.HashMap;

public class Main {
    public long[] getDistances(int[] arr) {
        long[] result=new long[arr.length];
        HashMap<Integer, ArrayList<Integer>> data=new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            ArrayList<Integer> integers = data.getOrDefault(arr[i], new ArrayList<>());
            integers.add(i);
            data.put(arr[i],integers);
        }
        for (ArrayList<Integer> value : data.values()) {
            long sum=0;
            int middle[]=new int[value.size()];
            int index=0;
            for (Integer integer : value) {
                sum+=integer;
                middle[index++]=integer;
            }
            long add=0;
            for (int i = 0; i < middle.length; i++) {
                result[middle[i]]=(long) middle[i]*i-add+(sum-add-(long) middle[i]*(middle.length-i));
                add+=middle[i];
            }

        }
        return result;
    }
}
